package db_live

import (
	"fmt"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/common/api_models"
	"longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/db/mysql/models/models_live"
	"strconv"
)

type BlockArea struct {
	ID         int    `json:"id"`
	CategoryID int    `json:"category_id"`
	Province   string `json:"province"`
	City       string `json:"city"`
}

func BlockData2Cache() {
	var ba = []BlockArea{}
	err := global2.Live().Table("db_live_banned_area").Find(&ba).Error
	if err != nil {
		global2.Log.Errorf("加载屏蔽库缓存失败:%+v", err)
	}
}

func Blocked(userArea *api_models.GetIpSearchResp, m *models_live.Live) *models_live.Live {
	if global2.Config.GetInt("area_check") != 1 {
		return m
	}
	m.Animation = 2

	if userArea.Province == "0" {
		userArea.Province = "未知地区"
	}

	if userArea.City == "0" {
		userArea.City = "未知地区"
	}

	if m.Matchid > 0 && (m.Categoryid == 1 || m.Categoryid == 2) {
		var check int64
		var err error

		if userArea.Province == "未知地区" || userArea.City == "未知地区" {
			// check cache
			if c, v := checkBlockCache(fmt.Sprintf("%s%d", string([]rune(userArea.Country)[:2])+"%", m.Categoryid)); c {
				check, _ = strconv.ParseInt(v, 10, 64)
			} else {
				err = global2.Live().Table("db_live_banned_area").Where("province like ? and category_id=?", string([]rune(userArea.Country)[:2])+"%", m.Categoryid).Count(&check).Error
				blockCache(fmt.Sprintf("%s%d", string([]rune(userArea.Country)[:2])+"%", m.Categoryid), check)
			}
		} else {
			if c, v := checkBlockCache(fmt.Sprintf("%s%s%d", string([]rune(userArea.Province)[:2])+"%", string([]rune(userArea.City)[0:2])+"%", m.Categoryid)); c {
				check, _ = strconv.ParseInt(v, 10, 64)
			} else {
				err = global2.Live().Table("db_live_banned_area").Where("province like ? and city like ? and category_id=?", string([]rune(userArea.Province)[:2])+"%", string([]rune(userArea.City)[0:2])+"%", m.Categoryid).Count(&check).Error
				blockCache(fmt.Sprintf("%s%s%d", string([]rune(userArea.Province)[:2])+"%", string([]rune(userArea.City)[0:2])+"%", m.Categoryid), check)
			}
		}
		if err != nil {
			global2.Log.Errorf("检查屏蔽库失败:%+v", err)
		}

		if check >= 1 {
			if m.Categoryid == 1 {
				m.PullUrl = fmt.Sprintf(_const.FootBallAnimationUrl, m.Matchid)
				m.PullFlvUrl = fmt.Sprintf(_const.FootBallAnimationUrl, m.Matchid)
			}

			if m.Categoryid == 2 {
				m.PullUrl = fmt.Sprintf(_const.BasketBallAnimationUrl, m.Matchid)
				m.PullFlvUrl = fmt.Sprintf(_const.BasketBallAnimationUrl, m.Matchid)
			}

			m.Animation = 1
		}

	}

	return m
}

func blockCache(key string, val int64) {
	//redis.GetRds().Set(key, val, time.Second*60)
}

func checkBlockCache(key string) (bool, string) {
	//res, _ := redis.GetRds().Get(key).Result()
	//if res != "" {
	//	return true, res
	//}
	//
	return false, ""
}
